package xuhaijia.lanou3g.autohome.db;
//                .-~~~~~~~~~-._       _.-~~~~~~~~~-.
//            __.'              ~.   .~              `.__
//          .'//                  \./                   \\`.
//        .'//            为什么坚持  想一想当初             \\`.
//      .'// .-~"""""""~~~~-._     |     _,-~~~~"""""""~-.  \\`.
//    .'//.-"                 `-.  |  .-'                 "-. \\`.
//  .'//______.============-..   \ | /   ..-============._______\\`.
//.'//____________________________\|/_____________________________\\`.
// 
//                             

import android.os.Handler;
import android.os.Looper;

import com.litesuits.orm.LiteOrm;
import com.litesuits.orm.db.assit.QueryBuilder;
import com.litesuits.orm.db.assit.WhereBuilder;

import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import xuhaijia.lanou3g.autohome.base.MyApp;
import xuhaijia.lanou3g.autohome.myself.Collection;
import xuhaijia.lanou3g.autohome.myself.History;

/**
 * Created by 7 on 16/8/31.
 */
public class DBToolForHistory {
    private static DBToolForHistory ourInstance;
    //liteOrm 对象,曾删改查方法 都操作此对象
    private LiteOrm mLiteOrm;
    //Handler 用来做线程切换,为了在主线程来执行回调,返回数据
    private Handler mHandler;

    //线程池
    ExecutorService threadPool
            = Executors.newFixedThreadPool(5);

    public static DBToolForHistory getInstance() {
        if (ourInstance == null) {
            synchronized (DBToolForHistory.class) {
                if (ourInstance == null) {
                    ourInstance = new DBToolForHistory();
                }
            }
        }

        return ourInstance;
    }

    private DBToolForHistory() {
        //初始化liteOrm对象
        //使用MyApp里的全局Context
        //第二个参数是 数据库的名字
        mLiteOrm = LiteOrm.newSingleInstance(MyApp.getContext()
                , "AutoHomeHistory.db");

        //初始化Handler
        //Handler的构造方法 参数如果传
        // Looper.getMainLooper()
        // 代表这个Handler 一定会回调到主线程
        // 属于严谨的写法
        mHandler = new Handler(Looper.getMainLooper());
    }

    //向数据库中插入一组数据
    public void insertHistory(final History history) {
        threadPool.execute(new Runnable() {
            @Override
            public void run() {
                mLiteOrm.insert(history);
            }
        });
    }
    public void insertCollection(final Collection collection) {
        threadPool.execute(new Runnable() {
            @Override
            public void run() {
                mLiteOrm.insert(collection);
            }
        });
    }

    // 删除一组数据
    public void deleteHistory(final History history) {
        threadPool.execute(new Runnable() {
            @Override
            public void run() {
                mLiteOrm.delete(history);
            }
        });
    }

    public void deleteHistoryBy(final String string, final String... value) {
        threadPool.execute(new Runnable() {
            @Override
            public void run() {
                mLiteOrm.delete(new WhereBuilder(History.class)
                        .where(string, value));
            }
        });
    }
    public void deleteCollectionBy(final String string, final String... value) {
        threadPool.execute(new Runnable() {
            @Override
            public void run() {
                mLiteOrm.delete(new WhereBuilder(Collection.class)
                        .where(string, value));
            }
        });
    }

    public void clearHistory() {

        ArrayList<History> histories = mLiteOrm.query(History.class);
        mLiteOrm.delete(histories);

    }
    public void clearCollection() {
        ArrayList<Collection> histories = mLiteOrm.query(Collection.class);
        mLiteOrm.delete(histories);
    }


    //查询所有学生
    //参数 需要一个接口对象,当查询成功之后
    //调用该接口对象的方法,来把数据返回回去
    public void queryAllHistory(final QueryListener queryListener) {
//        AsyncTask<Void,Void,ArrayList<Student>>
//                asyncTask = new AsyncTask<Void, Void, ArrayList<Student>>() {
//            @Override
//            protected ArrayList<Student> doInBackground(Void... voids) {
//
//                return mLiteOrm.query(Student.class);
//            }
//
//            @Override
//            protected void onPostExecute(ArrayList<Student> students) {
//                super.onPostExecute(students);
//                //主线程
//                queryListener.onQueryComplete(students);
//            }
//        };
//        asyncTask.execute();


        //使用Handler的方式

        threadPool.execute(new Runnable() {
            @Override
            public void run() {
                //在子线程中查询数据库,查询结果是students
                ArrayList<History> histories = mLiteOrm.query(History.class);
                //查询完成后 ,使用handler 在主线程回调接口对象
                //把数据传递出去
                //handler的post方法,接收一个runnable对象
                //会在主线程中 执行该runnable对象的run方法
//                mHandler.post(new Runnable() {
//                    @Override
//                    public void run() {
//                        queryListener.onQueryComplete(students);
//                    }
//                });
                mHandler.post(new HandlerRunnable(histories, queryListener));
            }
        });
    }


    //写一个类,作为handler的Runnable
    class HandlerRunnable implements Runnable {
        ArrayList<History> mHistories;
        QueryListener mQueryListener;

        //构造方法
        public HandlerRunnable(ArrayList<History> histories
                , QueryListener queryListener) {
            mHistories = histories;
            mQueryListener = queryListener;
        }

        @Override
        public void run() {
            mQueryListener.onQueryComplete(mHistories);
        }
    }

    //使用接口 来达到将数据异步的返回出去
    public interface QueryListener {
        void onQueryComplete(ArrayList<History> histories);
    }

    public void queryIsExist(final String string, final QueryListener queryListener) {
        threadPool.execute(new Runnable() {
            @Override
            public void run() {
                // 条件查询
                QueryBuilder<History> builder = new QueryBuilder<History>(History.class);
                builder.where(string, null); // 加入条件
                ArrayList<History> histories = mLiteOrm.query(builder);
                // 放到主线程回调
                mHandler.post(new HandlerRunnable(histories, queryListener));
            }
        });

    }

}
